package net.example.model.contract;

import com.oraycn.omcs.utils.BufferUtils;

import net.example.model.GroupType;

import java.nio.charset.StandardCharsets;
import java.util.List;

import io.netty.buffer.ByteBuf;

public class CreateGroupContract {

    public CreateGroupContract() { }
    public CreateGroupContract(GroupType type , String id, String name, String announce, List<String> members,boolean isPrivate) {
        this.GroupType = type;
        this.ID = id;
        this.Name = name;
        this.Announce = announce;
        this.Members = members;
        this.IsPrivate = isPrivate;
    }

    public GroupType GroupType ;

    public String ID ;

    public String Name ;

    public String Announce ;

    public List<String> Members ;

    public boolean IsPrivate;

    /**
     * 消息转byte
     *
     * @return
     */
    public byte[] serialize() throws Exception {
        byte[] bAnnounce = Announce.getBytes(StandardCharsets.UTF_8);
        byte[] bID = ID.getBytes(StandardCharsets.UTF_8);
        int contractLen = 4 + 4 + bAnnounce.length + 4 + 4 + bID.length + 4 +1;
        byte[] bName = Name.getBytes(StandardCharsets.UTF_8);
        contractLen += 4 + bName.length;
        ByteBuf body = BufferUtils.newBuffer();
        body.writeInt(0);
        body.writeInt(bAnnounce.length);
        body.writeBytes(bAnnounce);
        body.writeInt(this.GroupType.ordinal());
        body.writeInt(bID.length);
        body.writeBytes(bID);
        body.writeBoolean(IsPrivate);
        body.writeInt(Members.size());
        for (String memberID : Members) {
            byte[] bMemberID = memberID.getBytes(StandardCharsets.UTF_8);
            contractLen += 4 + bMemberID.length;
            body.writeInt(bMemberID.length);
            body.writeBytes(bMemberID);
        }
        body.writeInt(bName.length);
        body.writeBytes(bName);
        int totalLen = body.readableBytes() ;
        body.resetWriterIndex();
        body.writeInt(contractLen);
        byte[] result = new byte[totalLen];
        System.arraycopy(body.array(),0,result,0,result.length);
        return result;
    }

}

